/*
 * Copyright 2012-2014 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.jqd.framework.core.hessian.biz.action.support;

import java.lang.reflect.Method;

import com.esotericsoftware.reflectasm.MethodAccess;
import com.jqd.framework.core.exception.BusinessServiceException;
import com.jqd.framework.core.hessian.model.ServiceRequest;
import com.jqd.framework.core.hessian.model.ServiceResponse;

/**
 * 利用ReflectASM工具包进行方法调用，该工具进行方法调用时是通过操作字节码来实现的，所以比JDK中的反射方式调用要快
 * 
 * <p>
 * 该项目路径：<a href="http://code.google.com/p/reflectasm/">ReflectASM</a>
 * </p>
 * 
 * @author liaozhicheng.cn@gmail.com
 * @date 2012-8-24
 * @since 1.0
 * @see com.jqd.framework.core.hessian.biz.action.support.JdkReflectionMethodInvoker
 */
public class AsmReflectionMethodInvoker implements ActionMethodInvoker {
	
	private final String methodName;
	
	
	// private final Map<Class<?>, MethodAccess> methodAcessCache = new ConcurrentHashMap<Class<?>,
	// MethodAccess>();
	
	public AsmReflectionMethodInvoker(Method targetMethod) {
		this.methodName = targetMethod.getName();
	}
	
	
	@Override
	public ServiceResponse invoke(Method actionMethod, Object handler, ServiceRequest parameter)
			throws BusinessServiceException {
		
		MethodAccess methodAccess = MethodAccess.get(handler.getClass());
		// 很坑爹啊，经过简单的性能测试，如果每次调用的时候都需要执行 MethodAccess.get(handler.getClass());
		// 这段代码时，性能将不如JDK的反射快，这个操作是很耗时的操作
		// 但如果一旦执行完这段代码之后，循环执行（如1000000次）method.invoke() 调用将大大快于JDK的反射执行速度
		
		int methodIndex = methodAccess.getIndex(methodName);
		return (ServiceResponse) methodAccess.invoke(handler, methodIndex, parameter);
	}
	
}
